package com.macro.mall.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.macro.mall.dao.OmsOrderDao;
import com.macro.mall.dao.OmsOrderOperateHistoryDao;
import com.macro.mall.dto.*;
import com.macro.mall.mapper.OmsOrderMapper;
import com.macro.mall.mapper.OmsOrderOperateHistoryMapper;
import com.macro.mall.domain.OmsOrder;
import com.macro.mall.model.OmsOrderExample;
import com.macro.mall.domain.OmsOrderOperateHistory;
import com.macro.mall.service.OmsOrderOperateHistoryService;
import com.macro.mall.service.OmsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理Service实现类
 * Created by macro on 2018/10/11.
 */
@Service
public class OmsOrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements OmsOrderService {
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OmsOrderDao orderDao;
    @Autowired
    private OmsOrderOperateHistoryDao orderOperateHistoryDao;
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;
    @Autowired
    private OmsOrderOperateHistoryService operateHistoryService;

    @Override
    public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<OmsOrder> result = lambdaQuery()
                .eq(OmsOrder::getDeleteStatus, 0)
                .eq(queryParam.getOrderSn() != null && queryParam.getOrderSn() != "", OmsOrder::getOrderSn, queryParam.getOrderSn())
                .eq(queryParam.getStatus() != null, OmsOrder::getStatus, queryParam.getStatus())
                .eq(queryParam.getSourceType() != null, OmsOrder::getSourceType, queryParam.getSourceType())
                .eq(queryParam.getOrderType() != null, OmsOrder::getOrderType, queryParam.getOrderType())
                .like(queryParam.getCreateTime() != null && queryParam.getCreateTime() != "", OmsOrder::getCreateTime, queryParam.getCreateTime() + "%")
                .like(queryParam.getReceiverKeyword() != null && queryParam.getReceiverKeyword() != "", OmsOrder::getReceiverName, "%" + queryParam.getReceiverKeyword() + "%")
                .or().like(queryParam.getReceiverKeyword() != null && queryParam.getReceiverKeyword() != "", OmsOrder::getReceiverPhone, "%" + queryParam.getReceiverKeyword() + "%")
                .list();
        return result;
        /*
    <select id="getList" resultMap="com.macro.mall.mapper.OmsOrderMapper.BaseResultMap">
        SELECT *
        FROM
        oms_order
        WHERE
        delete_status = 0
        <if test="queryParam.orderSn!=null and queryParam.orderSn!=''">
            AND order_sn = #{queryParam.orderSn}
        </if>
        <if test="queryParam.status!=null">
            AND `status` = #{queryParam.status}
        </if>
        <if test="queryParam.sourceType!=null">
            AND source_type = #{queryParam.sourceType}
        </if>
        <if test="queryParam.orderType!=null">
            AND order_type = #{queryParam.orderType}
        </if>
        <if test="queryParam.createTime!=null and queryParam.createTime!=''">
            AND create_time LIKE concat(#{queryParam.createTime},"%")
        </if>
        <if test="queryParam.receiverKeyword!=null and queryParam.receiverKeyword!=''">
            AND (
            receiver_name LIKE concat("%",#{queryParam.receiverKeyword},"%")
            OR receiver_phone LIKE concat("%",#{queryParam.receiverKeyword},"%")
            )
        </if>
    </select>
         */
    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderDao.delivery(deliveryParamList);
        //添加操作记录
        List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                .map(omsOrderDeliveryParam -> {
                    OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                    history.setOrderId(omsOrderDeliveryParam.getOrderId());
                    history.setCreateTime(new Date());
                    history.setOperateMan("后台管理员");
                    history.setOrderStatus(2);
                    history.setNote("完成发货");
                    return history;
                }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(operateHistoryList);
        return count;
    }

    @Override
    public int close(List<Long> ids, String note) {
        OmsOrder record = new OmsOrder();
        record.setStatus(4);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        int count = orderMapper.updateByExampleSelective(record, example);
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:"+note);
            return history;
        }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(historyList);
        return count;
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrder record = new OmsOrder();
        record.setDeleteStatus(1);
        boolean update = lambdaUpdate().set(record.getId() != null, OmsOrder::getId, record.getId())
                .set(record.getMemberId() != null, OmsOrder::getMemberId, record.getMemberId())
                .set(record.getCouponId() != null, OmsOrder::getCouponId, record.getCouponId())
                .set(record.getOrderSn() != null, OmsOrder::getOrderSn, record.getOrderSn())
                .set(record.getCreateTime() != null, OmsOrder::getCreateTime, record.getCreateTime())
                .set(record.getMemberUsername() != null, OmsOrder::getMemberUsername, record.getMemberUsername())
                .set(record.getTotalAmount() != null, OmsOrder::getTotalAmount, record.getTotalAmount())
                .set(record.getPayAmount() != null, OmsOrder::getPayAmount, record.getPayAmount())
                .set(record.getFreightAmount() != null, OmsOrder::getFreightAmount, record.getFreightAmount())
                .set(record.getPromotionAmount() != null, OmsOrder::getPromotionAmount, record.getPromotionAmount())
                .set(record.getIntegrationAmount() != null, OmsOrder::getIntegrationAmount, record.getIntegrationAmount())
                .set(record.getCouponAmount() != null, OmsOrder::getCouponAmount, record.getCouponAmount())
                .set(record.getDiscountAmount() != null, OmsOrder::getDiscountAmount, record.getDiscountAmount())
                .set(record.getPayType() != null, OmsOrder::getPayType, record.getPayType())
                .set(record.getSourceType() != null, OmsOrder::getSourceType, record.getSourceType())
                .set(record.getStatus() != null, OmsOrder::getStatus, record.getStatus())
                .set(record.getOrderType() != null, OmsOrder::getOrderType, record.getOrderType())
                .set(record.getDeliveryCompany() != null, OmsOrder::getDeliveryCompany, record.getDeliveryCompany())
                .set(record.getDeliverySn() != null, OmsOrder::getDeliverySn, record.getDeliverySn())
                .set(record.getAutoConfirmDay() != null, OmsOrder::getAutoConfirmDay, record.getAutoConfirmDay())
                .set(record.getIntegration() != null, OmsOrder::getIntegration, record.getIntegration())
                .set(record.getGrowth() != null, OmsOrder::getGrowth, record.getGrowth())
                .set(record.getPromotionInfo() != null, OmsOrder::getPromotionInfo, record.getPromotionInfo())
                .set(record.getBillType() != null, OmsOrder::getBillType, record.getBillType())
                .set(record.getBillHeader() != null, OmsOrder::getBillHeader, record.getBillHeader())
                .set(record.getBillContent() != null, OmsOrder::getBillContent, record.getBillContent())
                .set(record.getBillReceiverPhone() != null, OmsOrder::getBillReceiverPhone, record.getBillReceiverPhone())
                .set(record.getBillReceiverEmail() != null, OmsOrder::getBillReceiverEmail, record.getBillReceiverEmail())
                .set(record.getReceiverName() != null, OmsOrder::getReceiverName, record.getReceiverName())
                .set(record.getReceiverPhone() != null, OmsOrder::getReceiverPhone, record.getReceiverPhone())
                .set(record.getReceiverPostCode() != null, OmsOrder::getReceiverPostCode, record.getReceiverPostCode())
                .set(record.getReceiverProvince() != null, OmsOrder::getReceiverProvince, record.getReceiverProvince())
                .set(record.getReceiverCity() != null, OmsOrder::getReceiverCity, record.getReceiverCity())
                .set(record.getReceiverRegion() != null, OmsOrder::getReceiverRegion, record.getReceiverRegion())
                .set(record.getReceiverDetailAddress() != null, OmsOrder::getReceiverDetailAddress, record.getReceiverDetailAddress())
                .set(record.getNote() != null, OmsOrder::getNote, record.getNote())
                .set(record.getConfirmStatus() != null, OmsOrder::getConfirmStatus, record.getConfirmStatus())
                .set(record.getDeleteStatus() != null, OmsOrder::getDeleteStatus, record.getDeleteStatus())
                .set(record.getUseIntegration() != null, OmsOrder::getUseIntegration, record.getUseIntegration())
                .set(record.getPaymentTime() != null, OmsOrder::getPaymentTime, record.getPaymentTime())
                .set(record.getDeliveryTime() != null, OmsOrder::getDeliveryTime, record.getDeliveryTime())
                .set(record.getReceiveTime() != null, OmsOrder::getReceiveTime, record.getReceiveTime())
                .set(record.getCommentTime() != null, OmsOrder::getCommentTime, record.getCommentTime())
                .set(record.getModifyTime() != null, OmsOrder::getModifyTime, record.getModifyTime())
                .eq(OmsOrder::getDeleteStatus, 0)
                .in(!ids.isEmpty(), OmsOrder::getId, ids).update();
        return ids.size();
    }

    @Override
    public OmsOrderDetail detail(Long id) {
        return orderDao.getDetail(id);
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        operateHistoryService.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        operateHistoryService.insert(history);
        return count;
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        order.setNote(note);
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(status);
        history.setNote("修改备注信息："+note);
        operateHistoryService.insert(history);
        return count;
    }
}
